import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'activity_calendar_logic.dart';

/// 活动日历页面
class ActivityCalendarView extends GetView<ActivityCalendarLogic> {
  const ActivityCalendarView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Get.back(),
        ),
        title: Obx(() => Text(
          '${controller.currentYear}',
          style: TextStyle(
            fontSize: 18.sp,
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        )),
        centerTitle: true,
      ),
      body: Obx(() {
        if (controller.isLoading) {
          return const Center(
            child: CircularProgressIndicator(color: Colors.white),
          );
        }

        return SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 星期标题
              _buildWeekHeader(),
              
              // 月份日历列表
              ...controller.getMonthsToDisplay().map((month) {
                return _buildMonthCalendar(month);
              }).toList(),
            ],
          ),
        );
      }),
    );
  }

  /// 构建星期标题
  Widget _buildWeekHeader() {
    final weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: weekDays.map((day) => SizedBox(
          width: 48.w,
          child: Text(
            day,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.grey[400],
            ),
          ),
        )).toList(),
      ),
    );
  }

  /// 构建月份日历
  Widget _buildMonthCalendar(int month) {
    final monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', 
                        '七月', '八月', '九月', '十月', '十一月', '十二月'];
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 月份标题
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          child: Text(
            monthNames[month - 1],
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.white,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
        
        // 日历网格
        _buildCalendarGrid(month),
        
        SizedBox(height: 20.h),
      ],
    );
  }

  /// 构建日历网格
  Widget _buildCalendarGrid(int month) {
    final year = controller.currentYear;
    final firstDayOfMonth = DateTime(year, month, 1);
    final lastDayOfMonth = DateTime(year, month + 1, 0);
    final daysInMonth = lastDayOfMonth.day;
    final firstWeekday = firstDayOfMonth.weekday % 7; // 0=周日, 1=周一, ...

    // 创建日历网格
    final List<Widget> dayWidgets = [];
    
    // 添加空白占位
    for (int i = 0; i < firstWeekday; i++) {
      dayWidgets.add(SizedBox(width: 48.w, height: 60.h));
    }
    
    // 添加日期
    for (int day = 1; day <= daysInMonth; day++) {
      final date = DateTime(year, month, day);
      final dateStr = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
      final dayData = controller.getDayData(dateStr);
      
      dayWidgets.add(_buildDayCell(day, dayData, dateStr));
    }

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Wrap(
        spacing: 0,
        runSpacing: 8.h,
        children: dayWidgets,
      ),
    );
  }

  /// 构建日期单元格
  Widget _buildDayCell(int day, Map<String, dynamic>? dayData, String dateStr) {
    final hasData = dayData != null;
    final steps = dayData?['steps'] ?? 0;
    final duration = dayData?['duration'] ?? 0;
    final calorie = dayData?['calorie'] ?? 0;
    
    // 计算进度
    final stepsProgress = (steps / 8000.0).clamp(0.0, 1.0);
    final caloriesProgress = (calorie / 400.0).clamp(0.0, 1.0);
    final timeProgress = (duration / 30.0).clamp(0.0, 1.0);

    return GestureDetector(
      onTap: hasData ? () => controller.onDateSelected(dateStr) : null,
      child: SizedBox(
        width: 48.w,
        height: 60.h,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 环状进度图
            SizedBox(
              width: 36.w,
              height: 36.w,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  // 外环 - 步数
                  SizedBox(
                    width: 36.w,
                    height: 36.w,
                    child: CircularProgressIndicator(
                      value: hasData ? stepsProgress : 0,
                      strokeWidth: 3.w,
                      backgroundColor: const Color(0xFF5b5c5c),
                      valueColor: AlwaysStoppedAnimation<Color>(
                        hasData && steps >= 8000
                            ? const Color(0xFFFFD700)
                            : (hasData ? const Color(0xFFFFD700).withOpacity(0.5) : Colors.grey[700]!)
                      ),
                      strokeCap: StrokeCap.round,
                    ),
                  ),
                  // 中环 - 卡路里
                  SizedBox(
                    width: 26.w,
                    height: 26.w,
                    child: CircularProgressIndicator(
                      value: hasData ? caloriesProgress : 0,
                      strokeWidth: 2.5.w,
                      backgroundColor: const Color(0xFF5b5c5c),
                      valueColor: AlwaysStoppedAnimation<Color>(
                        hasData && calorie >= 400
                            ? const Color(0xFFFF6B35)
                            : (hasData ? const Color(0xFFFF6B35).withOpacity(0.5) : Colors.grey[700]!)
                      ),
                      strokeCap: StrokeCap.round,
                    ),
                  ),
                  // 内环 - 时长
                  SizedBox(
                    width: 16.w,
                    height: 16.w,
                    child: CircularProgressIndicator(
                      value: hasData ? timeProgress : 0,
                      strokeWidth: 2.w,
                      backgroundColor: const Color(0xFF5b5c5c),
                      valueColor: AlwaysStoppedAnimation<Color>(
                        hasData && duration >= 30
                            ? const Color(0xFF00D4AA)
                            : (hasData ? const Color(0xFF00D4AA).withOpacity(0.5) : Colors.grey[700]!)
                      ),
                      strokeCap: StrokeCap.round,
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 4.h),
            // 日期数字
            Text(
              '$day',
              style: TextStyle(
                fontSize: 12.sp,
                color: hasData ? Colors.white : Colors.grey[600],
                fontWeight: hasData ? FontWeight.w600 : FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
